/**
 *
 */
package jp.seraph.jsade.task;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.NullArgumentException;

import jp.seraph.jsade.core.Agent;
import jp.seraph.jsade.core.Player;
import jp.seraph.jsade.core.World;
import jp.seraph.jsade.util.Executor;

/**
 * AgentTaskの実行を行うAgent
 *
 */
public class TaskAgent implements Agent {
    public TaskAgent(){
        mTaskList = new ArrayList<AgentTask>();
        mNewTask = true;
    }

    private boolean mNewTask;
    private List<AgentTask> mTaskList;

    /**
     *
     * @see jp.seraph.jsade.core.Agent#think(jp.seraph.jsade.core.World, jp.seraph.jsade.core.Player)
     */
    public void think(World aWorld, Player aPlayer) {
        if(mTaskList.size() == 0)
            return;

        final AgentTask tCurrentTask = mTaskList.get(0);
        if(mNewTask){
            if(!tCurrentTask.canExecute())
                return;

            mNewTask = false;
            Executor tListener = null;
            tListener = new Executor(){
                public void execute(){
                    mNewTask = true;
                    mTaskList.remove(0);
                }
            };

            tCurrentTask.addCompletedListener(tListener);
            tCurrentTask.addCanceledListener(tListener);
            tCurrentTask.init();
        }

        tCurrentTask.execute(aWorld, aPlayer);
    }

    public void InsertTask(AgentTask aTask){
        if(aTask == null)
            throw new NullArgumentException("aTask");

        mTaskList.add(aTask);
    }

    public int getTaskCount(){
        return mTaskList.size();
    }

    public AgentTask getTask(int aIndex){
        return mTaskList.get(aIndex);
    }
}
